package com.study.thread;

/**
 * @Description:
 * @Author King
 * @Date 2024/12/15 18:15
 */
/***
 * ReentrantLock锁可以绑定多个条件
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

public class TestReentrantLock4 {
    private static final Log log = LogFactory.getLog(TestReentrantLock4.class.getName());

    static ReentrantLock lock = new ReentrantLock();
    //创建两个回家条件：需要钱、需要票
    static Condition moneyCondition = lock.newCondition();
    static Condition ticketCondition = lock.newCondition();
    static Boolean havaMoney = false;//是否有钱
    static Boolean haveTicket = false;//是否有票

    public static void main(String[] args) throws InterruptedException {

        //线程 farmer1
        new Thread(() -> {
            log.info("--------第一个农民想回家--------");
            while (!havaMoney) {
                try {
                    lock.lock();
                    log.info("---------第一个农民没有钱，回不去家了，等钱---------");
                    for (int i = 0; i < 5; i++) {
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println("等待中..." + i);
                    }
                    moneyCondition.await();
                    log.info("---------第一个农民没有钱，有钱了，回家了---------");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    log.info("---------第一个农民，解锁---------");
                    lock.unlock();
                }
            }
        }, "farmer1").start();

        TimeUnit.SECONDS.sleep(1);

        //线程farmer2
        new Thread(() -> {
            log.info("--------第二个农民想回家--------");
            while (!haveTicket) {
                try {
                    lock.lock();
                    log.info("---------第二个农民没有票，回不去家了，等票---------");
                    ticketCondition.await();
                    log.info("---------第二个农民没有票，有票了，回家了---------");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    log.info("---------第二个农民，解锁---------");
                    lock.unlock();
                }
            }
        }, "farmer2").start();

        //主线程12306睡一会
        TimeUnit.SECONDS.sleep(1);
        try {
            lock.lock();
            havaMoney = true;
            log.info("---------第一个农民有钱了，唤醒他可以回家了---------");
            moneyCondition.signal();//唤醒等钱的farm1线程执行回家。

            haveTicket = true;
            log.info("---------第二个农民有票了，唤醒他可以回家了---------");
            ticketCondition.signal();//唤醒等票的farm2线程执行回家。
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

